package com.nc.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.nc.user.model.entity.FrmPermissions;
import com.plug.BeanUtil;
import com.plug.result.ReqPage;
import com.plug.result.RetResponse;
import com.plug.result.RetResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.nc.user.dao.FrmDataResourcesDao;
import com.nc.user.dao.FrmPermissionsDao;
import com.nc.user.model.dto.DataResourcesDto;
import com.nc.user.model.entity.FrmDataResources;
import com.nc.user.service.DataResourceService;
import com.nc.user.service.ShiroService;

import javax.transaction.Transactional;
import java.util.List;

/**
 * 创建人:    xvzhe
 * 创建时间:
 * 修改时间:
 * 版本:      v1.0
 */
@Service
public class DataResourceServiceImpl implements DataResourceService {
    @Autowired
    private FrmDataResourcesDao dataResourcesDao;
    @Autowired
    private FrmPermissionsDao permissionsDao;
    @Autowired
    private ShiroService shiroService;

    @Override
    @Transactional
    public RetResult save(DataResourcesDto dataResourcesDto) {
        try {
            FrmDataResources dataResources = BeanUtil.convertToBean(dataResourcesDto, FrmDataResources.class);
            dataResources.setType(FrmDataResources.Type.valueOf(dataResourcesDto.getType()));
            dataResources = dataResourcesDao.save(dataResources);
            List<FrmPermissions> permissions = permissionsDao.findByCodeIn(dataResourcesDto.getPermissions());
            FrmDataResources finalDataResources = dataResources;
            permissions.stream().forEach(ls -> {
                dataResourcesDao.insertPermissionsData(finalDataResources.getId(), ls.getId());
            });
            shiroService.flush();
            return RetResponse.makeOKRsp();
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return RetResponse.makeErrRsp("保存失败");
        }
    }

    @Override
    public RetResult findAll(ReqPage reqPage) {
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains());
        Example<FrmDataResources> example = Example.of(JSON.parseObject(reqPage.getCommon().toJSONString(), FrmDataResources.class), matcher);
        Pageable pageable = PageRequest.of(reqPage.getPage() - 1, reqPage.getLimit(), Sort.Direction.DESC, "type");
        Page<FrmDataResources> users = dataResourcesDao.findAll(example, pageable);
        return RetResponse.makeRsp(0, "成功", users.getContent(), (int) users.getTotalElements());
    }
}
